<template>
  <div class="checklists1">
    <van-notice-bar
        mode="closeable"
        background="-moz-linear-gradient(90deg,#F83600 0%,#F9D423 100%)"
        style="height: 40px"
    >徽商银行股份有限公司向我司申请为您投保员工福利保障计划，为保障您的权益，请您认真准确填写您的个人信息，实际是否可参与单位承保或标体承保，需健告信息返回评估后确认
    </van-notice-bar>
    <van-panel title="个人基础信息" class="paneltitle"/>
    <van-form ref="form">
      <van-field
          v-model="form.name"
          name="姓名"
          label="姓名"
          placeholder="姓名"
          required
          :rules="[{ required: true, message: '请填写姓名' }]"
      />
      <van-field
          name="radio"
          v-model="form.idType"
          label="证件类型"
          required
          :rules="[{ required: true, message: '请选择证件类型' }]"
      >
        <template #input>
          <van-radio-group v-model="form.idType" direction="horizontal">
            <van-radio name="1" shape="square">身份证</van-radio>
            <van-radio name="0" shape="square" disabled>其它</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
          v-model="form.idNumber"
          name="证件号码"
          label="证件号码"
          placeholder="证件号码"
          required
          :rules="telRules"
          @input="filterInput"
          type="text"
      />
      <div style="margin: 16px">
        <van-button
            block
            type="info"
            native-type="submit"
            @click="onCheck1"
            size="normal"
            class="onButton"
            :loading="Isloading"
            loading-text="加载中..."
        >下一步
        </van-button>
      </div>
    </van-form>
    <van-dialog
        v-model="show"
        title="温馨提示"
        show-cancel-button
        @confirm="confirm"
        @cancel="cancel"
    >
      <!-- <img src="https://img01.yzcdn.cn/vant/apple-3.jpg" /> -->
      <p class="dialog-show">
        您将进入<span class="home-text">徽商银行股份有限公司</span>员工专属阳光人寿健康告知信息填写页面，非该企业员工请绕行呦!
      </p>
    </van-dialog>
    <!-- <div class="loading-container">
      <van-loading color="#0094ff" />
    </div> -->
  </div>
</template>

<script>
import Cookies from 'js-cookie';
import {getSignUrl, getOpenid, checkUser, validityEnter} from "@/api/list";
import {FE_HOME_URL} from "@/utils/request";
import {mapState, mapActions} from "vuex";
// import Vue from "vue";

export default {
  data() {
    return {
      form: {
        idType: "1",
        name: "",
        idNumber: "",
      },
      OpenidValue: "",
      show: true,
      telRules: [
        {
          required: true,
          message: "身份证不能为空",
          trigger: "onBlur",
        },
        {
          // 自定义校验规则
          validator: (value) => {
            return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
                value
            );
          },
          message: "请输入正确格式的身份证",
          trigger: "onBlur",
        },
      ],
      Isloading:false
    };
  },
  created() {
    // 判断是否在有效期
    this.validityEnter();

    this.initData();
  },

  computed: {
    // 映射 Vuex store 中的 isDebug 状态到计算属性
    ...mapState(["isDebug"]),
  },
  methods: {
    initData() {
      var isDebugFlag = this.$isDebugFlag;
      if (isDebugFlag) {
        this.form.name = "田鹏飞";
        this.form.idType = "1";
        this.form.idNumber = "130324199209260039";
      }
    },
    validityEnter() {
      var isDebugFlag = this.$isDebugFlag;
      console.info("isDebugFlag:" + isDebugFlag);

      validityEnter()
          .then((res) => {
            console.info("validityEnter res");
            console.info(res);
            let {code, success} = res;
            if (code !== 0 && success !== true) {
              console.info("kong");
              this.$router.push("/kong");
            } else {
              console.info("checkOpenId");
              this.checkOpenId();
            }
            console.log("validityEnter", res);
          })
          .catch((err) => {
            console.log(err);
          });
    },
    onCheck1() {
      //  白名单接口
      checkUser(this.form)
          .then((res) => {
            // 校验
            this.$refs.form
                .validate()
                .then(() => {
                  this.Isloading=true
                  let {code, success, obj} = res;
                  if (code === -1 && obj !== null && success === false) {
                    console.log("在白名单内，已经完成填写");
                    this.$dialog.alert({
                      title: "温馨提示",
                      message:
                          "您已完成填写，无需重复填写，如有问题请与我司服务人员联系",
                    });

                    // let pdfUrl = res.obj;
                    // console.log("pdfUrl", pdfUrl);
                    // this.$router.push({name: "signany", params: {pdfUrl}});
                    this.$router.push({name: "signany", params: {
                        idType:this.form.idType,
                        name: this.form.name,
                        idNumber: this.form.idNumber,
                    }});
                    // this.$router.push({name: "signany"});
                    // this.$toast.fail(res.msg);
                  } else if (code === 0 && success === true) {
                    console.log("在白名单内，没有完成填写");
                    this.form = {...this.form, Openid: this.OpenidValue};
                    this.$emit("onShowCheck", false, this.form);
                    sessionStorage.setItem("InsName", this.form.name);
                    // this.$toast.success("提交成功");
                  } else if (code === -1 && obj === null && success === false) {
                    console.log("不在白名单内");
                    this.$dialog.alert({
                      title: "温馨提示",
                      message: "您无法继续填写，如有问题，请与我司服务人员联系",
                    });
                  }
                  this.Isloading=false
                })
                .catch((err) => {
                  console.info(err)
                  this.$dialog.alert({
                    title: "温馨提示",
                    message: "信息未补充完整/有误",
                  });
                  this.Isloading=false
                });
          })
          .catch((err) => {
            console.log(err);
          });
    },
    confirm() {
      console.log("确定键");
      this.show = false;
    },
    cancel() {
      console.log("取消键");
      // window.opener = null;
      // window.open("about:blank", "_self");
      // window.location.replace('about:blank');
      // window.close();
      var userAgent = navigator.userAgent;
      // console.log(userAgent);
      // return
      if (
          userAgent.indexOf("Firefox") != -1 ||
          userAgent.indexOf("Chrome") != -1
      ) {
        window.location.href = "about:blank";
      } else if (
          userAgent.indexOf("Android") > -1 ||
          userAgent.indexOf("Linux") > -1
      ) {
        window.opener = null;
        window.open("about:blank", "_self", "").close();
      } else {
        window.opener = null;
        // window.open("about:blank", "_self");
        window.location.replace("about:blank");
        window.close();
      }
    },
    checkOpenId() {
      console.info("checkOpenId enter");
      // todo 111 - 测试 这里openid先写死
      // 1. 先判断是否有openid，如果有，不做其他的操作
      // todo 测试使用，先remove掉
      // window.sessionStorage.removeItem("sh-openid");

      var isDebugFlag = this.$isDebugFlag;
      if (isDebugFlag) {
        window.sessionStorage.setItem(
            "sh-openid",
            "oslIft5CZfxtT-0EJrSMw4yV2sVc"
        );
        Cookies.set('sh-h5token', "oslIft5CZfxtT-0EJrSMw4yV2sVc");
      }
      // window.sessionStorage.setItem("sh-openid", "oslIft5CZfxtT-0EJrSMw4yV2sVc");
      this.OpenidValue = window.sessionStorage.getItem("sh-openid");
      // alert("checkOpenId openID:" + this.OpenidValue);
      if (this.OpenidValue) {
        // alert("有openid,执行操作:" + this.OpenidValue);
        console.log("有openid,执行操作:" + this.OpenidValue);
        return;
      }

      // alert("no有openid,执行操作:" + this.OpenidValue);
      // alert("OpenidValue:" + this.OpenidValue);
      var url = window.location.href;
      console.info("url:" + url);

      //2. 如果没有openid，则判断参数中是否有sign参数
      // 使用正则表达式提取 sign 参数
      var match = url.match(/[?&]sign=([^&#]*)|sign=([^&#]*)/);
      var signValue = match ? match[1] || match[2] : null; // 获取 sign 的值
      // 去掉最后一个 /
      if (signValue && signValue.endsWith("/")) {
        signValue = signValue.slice(0, -1); // 使用 slice 去掉最后一个字符
      }

      // alert("sign:" + signValue);
      console.log("signValue:" + signValue);

      if (signValue) {
        // alert("getOpenid enter")
        // 请求获取openId
        // 如果有sign值，则请求获取openid
        // alert("请求signValue" + signValue);
        getOpenid(signValue)
            .then((res) => {
              // console.log(res, sign);
              if (res.code == 0 && res.obj != null) {
                var openid = res.obj;
                console.log("openid:" + openid);
                window.sessionStorage.setItem("sh-openid", openid);
                Cookies.set('sh-h5token', openid);

                // var openidTmp = window.sessionStorage.getItem("sh-openid");
                // alert("signValue openidTmp:" + openidTmp);
                window.location.href = FE_HOME_URL;
              } else {
                console.log("没有获取到openid");
              }
            })
            .catch((err) => {
              console.log(err);
            });
      } else {
        // 没有signValue,则请求获取sign
        // todo 这里要做一个判断和验证，如果用户一直没有进行授权，这里可能会一直进行循环获取sign
        // alert("url:"+this.$route.query.url)
        // var fullPath = window.location.href;
        // alert("fullPath:" + fullPath);
        // alert("getSignUrl")
        console.log("没有openid,执行操作");
        getSignUrl()
            .then((res) => {
              if (res.code == 0 && res.obj != null) {
                console.log("window.location.href redirect url" + res.obj);
                var href = res.obj;
                // alert("window.location.href redirect url href:" + href);
                //进行跳转---必要时放开
                window.location.href = href;
              } else {
                console.log("没有获取到sign");
              }
            })
            .catch((err) => {
              console.log(err);
            });
      }
    },
    filterInput(value) {
      this.form.idNumber = value.replace(/[^0-9a-zA-Z]/g, '');
    }
  },
};
</script>

<style lang="scss" scoped>
.checklists1 {
  .dialog-show {
    text-align: center;
    padding: 5px 10px;
    font-size: 17px !important;
  }

  .home-text {
    color: rgb(225, 159, 28);
    font-size: 17px;
  }

  ::v-deep .van-field__control {
    display: inline-block;
    height: 40px;
    line-height: 40px;
    font-size: 17px !important;
  }

  ::v-deep .van-field__label {
    display: inline-block;
    height: 40px;
    line-height: 40px;
    font-weight: bold;
    font-size: 17px !important;
  }

  ::v-deep .van-radio-group {
    height: 40px;
    line-height: 40px;
    font-size: 17px !important;
  }

  ::v-deep .van-cell--required::before {
    padding: 5px 0;
  }

  .paneltitle {
    font-weight: bolder;
  }

  .van-cell {
    font-size: 20px !important;
  }

  .onButton {
    font-size: 17px !important;
  }
  // .loading-container {
  //   position: fixed;
  //   top: 50%;
  //   left: 50%;
  //   transform: translate(-50%, -50%);
  //   background-color: rgba(255, 255, 255, 0.8);
  //   z-index: 1000;
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;
  //   padding: 20px;
  // }
}
</style>
